package org.singledog.permission.filter;

import com.alibaba.fastjson.JSONObject;
import org.singledog.permission.core.PermissionApplicationContext;
import org.singledog.permission.core.PermissionSource;
import org.singledog.permission.exception.PermissionExceptionHolder;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * PermissionFilter顶级接口,建议如果自定义的话继承自该filter
 *
 * @author liuzheming
 * @since 2021.9.17
 */
public abstract class PermissionFilter implements Filter {

    public void init(FilterConfig filterConfig) throws ServletException {

    }

    /**
     * 执行核心filter逻辑
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        try {
            HttpServletRequest request = (HttpServletRequest) servletRequest;
            HttpServletResponse response = (HttpServletResponse) servletResponse;
            String requestURI = request.getRequestURI() + "/" + request.getMethod().toLowerCase();
            List<PermissionSource> needPermissions = PermissionApplicationContext.getPermissionUri(requestURI);
            if (needPermissions == null || needPermissions.size() == 0) {
                filterChain.doFilter(request, response);
                return;
            }
            List<PermissionSource> havePermissions = preHandFilter(request, response, filterChain);
            boolean isSuccess = handlerFilter(needPermissions, havePermissions);
            afterHandFilter(request, response, filterChain, isSuccess);
        } catch (PermissionExceptionHolder.PermissionException e) {
            HttpServletResponse response = (HttpServletResponse) servletResponse;
            response.setContentType("application/json");
            JSONObject responseJSON = new JSONObject();
            responseJSON.put("code",e.getCode());
            responseJSON.put("message",e.getMessage());
            responseJSON.put("success",false);
            PrintWriter writer = response.getWriter();
            writer.write(responseJSON.toJSONString());
            writer.flush();
            writer.close();
        }
    }

    public void destroy() {

    }

    protected abstract List<PermissionSource> preHandFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException;

    protected abstract void afterHandFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain, boolean isSuccess) throws IOException, ServletException;

    /**
     * filter权限校验
     */
    protected boolean handlerFilter(List<PermissionSource> needPermissions, List<PermissionSource> havePermissions) {
        if (needPermissions == null || needPermissions.size() == 0) {
            return true;
        } else {
            if (needPermissions.stream().allMatch(a -> havePermissions.stream().anyMatch(b -> b.implies(a))) || havePermissions.stream().anyMatch(a -> a.implies(new PermissionSource("admin.*")))) {
                return true;
            } else {
                return false;
            }
        }
    }
}
